package org.example.traffic.videoInfo;

import org.example.traffic.videoInfo.Video;
import org.example.traffic.videoInfo.VideoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class VideoService {

    @Autowired
    private VideoRepository videoRepository;

    private final Path rootLocation = Paths.get("src/main/resources/static/uploads");

    public void init() {
        try {
            Files.createDirectories(rootLocation);
        } catch (IOException e) {
            throw new RuntimeException("Could not initialize storage!");
        }
    }

    public Video store(MultipartFile file) {
        try {
            String filename = file.getOriginalFilename();
            Path destinationFile = rootLocation.resolve(Paths.get(filename)).normalize().toAbsolutePath();
            file.transferTo(destinationFile);

            Video video = new Video();
            video.setName(filename);
            video.setFilePath("/uploads/" + filename); // 设置可通过 URL 访问的路径
            video.setUploadTime(LocalDateTime.now());

            return videoRepository.save(video);
        } catch (IOException e) {
            throw new RuntimeException("Failed to store file.", e);
        }
    }
    // 分页查询视频
    public Page<Video> getVideos(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return videoRepository.findAll(pageable);
    }
    public List<Video> loadAll() {
        return videoRepository.findAll();
    }
}